package com.explore.demo.utils;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.explore.demo.cache.RedisCache;
import com.explore.demo.service.impl.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author gaolainan
 */
@Component
public class MessageUtils
{

    @Resource
    private RedisCache redisCache;

    /**
     * 打印日志文件
     */
    private final Logger logger = LoggerFactory.getLogger(MessageUtils.class);

    public boolean getMessageRequest(String phone, String code){
        // 连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4GEazCitfhAJsFTb4CXk", "ghIdRlimc8nFxlz2AJq8kM7QHtho0r");
        IAcsClient client = new DefaultAcsClient(profile);

        // 模板
        String templateCode = "SMS_205877419";

        // 随机验证码 设置过期时间为一分钟
        // HttpSession session = ExploreUtils.getSession();
        // session.setAttribute(phone,code);
        // session.setMaxInactiveInterval(60);

        //以手机号为key 验证码内容为value
        redisCache.setCacheObject(phone, code, 60, TimeUnit.SECONDS);
        logger.info("验证码存入缓存成功,设置过期时间为 60s =========> : "+code);

        ConcurrentHashMap<String, Object > param = new ConcurrentHashMap<>(1);
        param.put("code",code);


        CommonRequest request = new CommonRequest();

        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        // 自定义的参数（手机号、验证码、签名、模板）

        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "探索商城");
        request.putQueryParameter("TemplateCode", templateCode);

        // 短信验证码
        request.putQueryParameter("TemplateParam", JSON.toJSONString(param));
        try {
            CommonResponse response = client.getCommonResponse(request);
            logger.info("发送的验证码的内容为：===> "+response.getData());
        }
        catch (ClientException e) {
            e.printStackTrace();
        }
        return true;
    }
}
